package com.tairan.chapter.web.config.shiro;

import com.tairan.chapter.web.model.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author litairan
 * @date 2018-07-13 11:35
 */
public class SystemAuthorizingRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.getPrimaryPrincipal();
        // 添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 添加单个角色信息
        simpleAuthorizationInfo.addRole("admin");
        // 批量添加角色信息
        simpleAuthorizationInfo.addRoles(Stream.of("admin", "role").collect(Collectors.toList()));
        // 添加单个权限标识
        simpleAuthorizationInfo.addStringPermission("*:*");
        // 批量添加权限标识
        simpleAuthorizationInfo.addStringPermissions(Stream.of("sys:role", "sys:user").collect(Collectors.toList()));
        return simpleAuthorizationInfo;
    }

    /**
     * 定义如何获取用户信息的业务逻辑，给shiro做登录
     * 主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String nickname = token.getPrincipal().toString();
        User user = new User();
        user.setId(2L);
        user.setName("litairan");
        // 判断用户信息是否存在
        return new SimpleAuthenticationInfo(user, "123456", getName());
    }

//    @PostConstruct
//    public void initCredentialsMatcher() {
//        // 该句作用是重写Shiro的密码验证，让Shiro用我自己的验证
//        setCredentialsMatcher(new CustomCredentialsMatcher());
//    }

}
